package com.hzf.wxplatform.web.controller;


import com.github.wenhao.geohash.GeoHash;
import com.hzf.api.rpc.api.ApiService;
import com.hzf.common.util.*;
import com.hzf.config.dao.model.ConfigRegion;
import com.hzf.config.dao.model.ConfigRegionExample;
import com.hzf.config.rpc.api.ConfigApiService;
import com.hzf.ucenter.dao.model.*;
import com.hzf.wxplatform.common.WxplatformResult;
import com.hzf.wxplatform.common.WxplatformResultConstant;
import com.hzf.wxplatform.common.utils.UcenterUserUtils;
import com.hzf.wxplatform.common.utils.WxGetGpsUtils;
import com.hzf.wxplatform.dao.model.WxUser;
import io.swagger.models.auth.In;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.hzf.common.base.BaseController;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.security.krb5
        .Config;

/**
 * 首页控制器
 * Created by Jiangxueli on 2017/3/19.
 */
@Controller
public class IndexController extends BaseController {
    @Autowired
    ApiService apiService;
    private final static String HZF_WX_CLIENT_SESSION_ID = "hzf-upms-client-session-id";


    @RequestMapping(value = "/wxOauth/getOpenid", method = RequestMethod.GET)
    public String getOpenid(HttpServletRequest request, HttpServletResponse response, Model model) {
        HttpSession session = request.getSession();
        UcenterUser ucenterUser = new UcenterUser();
        UcenterUser ucenterUserCity = new UcenterUser();
        Integer userID = (Integer) session.getAttribute(HZF_WX_CLIENT_SESSION_ID + "userid");
        System.out.println(userID);
        if (userID != null) {
            String key = "user" + userID.toString();
            byte[] b = RedisUtil.get(key.getBytes());
            if (b != null) {
                ucenterUser = (UcenterUser) ByteUtils.ByteToObject(b);
            }
        }
        String state = request.getParameter("state");
        if (ucenterUser.getUserNumber() == null) {
            UcenterUser ucenterUserOne = new UcenterUser();
            //创建session对象
            String code = request.getParameter("code");
            JSONObject jsonObject = WeixinUtil.dogetUserOpenid(code);
            WxUser wxUser = (WxUser) JSONObject.toBean(jsonObject, WxUser.class);
            UcenterUserOauth ucenterUserOauth = new UcenterUserOauth();
            ucenterUserOauth.setCity(wxUser.getCity());
            ucenterUserOauth.setProvince(wxUser.getProvince());
            ucenterUserOauth.setOpenId(wxUser.getOpenid());
            ucenterUserOauth = apiService.insertUserOauth(ucenterUserOauth);
            if (null == ucenterUserOauth) {
                ucenterUserOauth = apiService.selectOauth(wxUser.getOpenid());
                ucenterUser = selectCity(ucenterUserOauth.getId(), state);

                if (UcenterUserUtils.isLogin(ucenterUser.getLoginStatus())) {

                    toRedisAddress(ucenterUser);
                    toRedisUser(ucenterUser, session);
                    model.addAttribute("user", ucenterUser);
                    return thymeleaf(IndexUtil.indesIs(state));
                } else {
                    System.out.println("您已被封禁");
                    toRedisUser(ucenterUser, session);
                    toRedisAddress(ucenterUser);
                    model.addAttribute("user", ucenterUser);
                    return thymeleaf(IndexUtil.indesIs(state));
                }
            }
            long time = System.currentTimeMillis();
            System.out.println(time);
            ucenterUserOne.setCreateDate(time);
            ucenterUserOne.setUpdateTime(time);
            String numberId = UUID.randomUUID().toString().replaceAll("-", "");
            ucenterUserOne.setUserNumber(numberId);
            ucenterUserOne.setLoginStatus(0);
            ucenterUserOne.setUserGade(0);
            ucenterUserOne.setUserStatus(0);
            ucenterUserOne.setUserThirdId(ucenterUserOauth.getId());
            ucenterUserOne.setNickName(wxUser.getNickname());
            ucenterUserOne.setUserHead(wxUser.getHeadimgurl());
            ucenterUserOne.setSex(wxUser.getSex());
            ucenterUser = apiService.insertUser(ucenterUserOne);
            if (null == ucenterUser) {
                ucenterUserOauth = apiService.selectOauth(wxUser.getOpenid());
                ucenterUser = selectCity(ucenterUserOauth.getId(), state);

                if (UcenterUserUtils.isLogin(ucenterUser.getLoginStatus())) {
                    toRedisAddress(ucenterUser);
                    toRedisUser(ucenterUser, session);
                    model.addAttribute("user", ucenterUser);
                    return thymeleaf(IndexUtil.indesIs(state));
                } else {
                    System.out.println("您已被封禁");
                    toRedisAddress(ucenterUser);
                    toRedisUser(ucenterUser, session);
                    model.addAttribute("user", ucenterUser);
                    System.out.println(thymeleaf(IndexUtil.indesIs(state)));
                    return thymeleaf(IndexUtil.indesIs(state));
                }
            }
            ucenterUserOne.setId(ucenterUser.getId());
            toRedisAddress(ucenterUserOne);
            toRedisUser(ucenterUserOne, session);
            model.addAttribute("user", ucenterUserOne);
            return thymeleaf(IndexUtil.indesIs(state));
        } else {
            if (UcenterUserUtils.isLogin(ucenterUser.getLoginStatus())) {
                UcenterAuthInfoExample example = new UcenterAuthInfoExample();
                example.createCriteria().andUserIdEqualTo(ucenterUser.getId());
                UcenterAuthInfoExample example1 = new UcenterAuthInfoExample();
                example1.createCriteria().andUserIdEqualTo(ucenterUser.getId()).andAuthTypeEqualTo(Integer.parseInt(state));
                List<UcenterAuthInfo> list = apiService.selectUcenterAuthInfo(example);
                List<UcenterAuthInfo> list1 = apiService.selectUcenterAuthInfo(example1);
                UcenterUserCityExample ucenterUserCityExample = new UcenterUserCityExample();
                ucenterUserCityExample.createCriteria().andUserIdEqualTo(ucenterUser.getId());
                UcenterUserCity  ucenterUserCities = apiService.getUserCity(ucenterUserCityExample);
                UcenterUserCityExample ucenterUserCityExample1 = new UcenterUserCityExample();
                ucenterUserCityExample1.createCriteria().andUserIdEqualTo(ucenterUser.getId());
                List<UcenterUserCity> citylist  = apiService.selectUserCity(ucenterUserCityExample);
                if(null!=citylist&&0!=citylist.size()){
                    ucenterUser.setUcenterUserCities(citylist);
                }
                if(null!=list1&&0!=list1.size()){
                    ucenterUser.setAuthInfo(list1.get(0).getAuthType());
                    ucenterUser.setAuthInfoId(list1.get(0).getId());
                }else{
                    ucenterUser.setAuthInfo(null);
                    ucenterUser.setAuthInfoId(null);
                }
                if(null!=list&&0!=list.size()){
                    ucenterUser.setUcenterAuthInfos(list);
                }else{
                    ucenterUser.setUcenterAuthInfos(null);
                }
                if(null!=ucenterUserCities){
                    ConfigRegionExample configRegionExample = new ConfigRegionExample();
                    configRegionExample.createCriteria().andRegionIdEqualTo(ucenterUserCities.getCityId());
                    ConfigRegion configRegion = apiService.selectAddressRegion(configRegionExample);
                    ucenterUser.setRegionId(configRegion.getRegionId());
                    ucenterUser.setRegionName(configRegion.getRegionName());
                    ucenterUser.setRegionNumber(configRegion.getRegionNumber().intValue());
                }else{    ucenterUser.setRegionId(0);
                    ucenterUser.setRegionName("");
                    ucenterUser.setRegionNumber(0);

                }
                toRedisAddress(ucenterUser);
                toRedisUser(ucenterUser, session);
                model.addAttribute("user", ucenterUser);
                System.out.println(thymeleaf(IndexUtil.indesIs(state)));
                return thymeleaf(IndexUtil.indesIs(state));
            } else {
                System.out.println("您已被封禁");
                UcenterAuthInfoExample example = new UcenterAuthInfoExample();
                example.createCriteria().andUserIdEqualTo(ucenterUser.getId());
                UcenterAuthInfoExample example1 = new UcenterAuthInfoExample();
                example1.createCriteria().andUserIdEqualTo(ucenterUser.getId()).andAuthTypeEqualTo(Integer.parseInt(state));
                List<UcenterAuthInfo> list = apiService.selectUcenterAuthInfo(example);
                List<UcenterAuthInfo> list1 = apiService.selectUcenterAuthInfo(example1);
                UcenterUserCityExample ucenterUserCityExample = new UcenterUserCityExample();
                ucenterUserCityExample.createCriteria().andUserIdEqualTo(ucenterUser.getId());
                UcenterUserCity  ucenterUserCities = apiService.getUserCity(ucenterUserCityExample);
                UcenterUserCityExample ucenterUserCityExample1 = new UcenterUserCityExample();
                ucenterUserCityExample1.createCriteria().andUserIdEqualTo(ucenterUser.getId());
                List<UcenterUserCity> citylist  = apiService.selectUserCity(ucenterUserCityExample);
                if(null!=citylist&&0!=citylist.size()){
                    ucenterUser.setUcenterUserCities(citylist);
                }
                if(null!=list1&&0!=list1.size()){
                    ucenterUser.setAuthInfo(list1.get(0).getAuthType());
                    ucenterUser.setAuthInfoId(list1.get(0).getId());
                }
                if(null!=list&&0!=list.size()){
                    ucenterUser.setUcenterAuthInfos(list);
                }
                if(null!=ucenterUserCities){
                    ConfigRegionExample configRegionExample = new ConfigRegionExample();
                    configRegionExample.createCriteria().andRegionIdEqualTo(ucenterUserCities.getCityId());
                    ConfigRegion configRegion = apiService.selectAddressRegion(configRegionExample);
                    ucenterUser.setRegionId(configRegion.getRegionId());
                    ucenterUser.setRegionName(configRegion.getRegionName());
                    ucenterUser.setRegionNumber(configRegion.getRegionNumber().intValue());
                }
                toRedisAddress(ucenterUser);
                toRedisUser(ucenterUser, session);
                model.addAttribute("user", ucenterUser);
                System.out.println(thymeleaf(IndexUtil.indesIs(state)));
                return thymeleaf(IndexUtil.indesIs(state));

            }


        }

    }

    @RequestMapping(value = "/wxOauth/getSing", method = RequestMethod.POST)
    @ResponseBody
    public Object getSing(Model model, String url, HttpServletRequest request) {
        String noncestr = UUID.randomUUID().toString();
        String timestamp = Long.toString(System.currentTimeMillis() / 100);
        String signature = WeixinUtil.dogetJsapiTicket(noncestr, timestamp, url);
        model.addAttribute("noncestr", noncestr);
        model.addAttribute("timestamp", timestamp);
        model.addAttribute("signature", signature);
        model.addAttribute("appId", PropertiesFileUtil.getInstance("wx").get("wx_appid"));
        return new WxplatformResult(WxplatformResultConstant.SUCCESS, model);
    }

    public UcenterUser selectCity(int id, String state) {
        System.out.println("当前state" + state);
        UcenterUser ucenterUser = new UcenterUser();
        if (state == "2") {
            ucenterUser = apiService.selectRegionUser(id, Integer.parseInt(state));

        } else if (state == "3") {
             ucenterUser = apiService.selectRegionUser(id, Integer.parseInt(state));
        } else if (state == "4") {
             ucenterUser = apiService.selectRegionUser(id, Integer.parseInt(state));
        } else if (state == "5") {
             ucenterUser = apiService.selectRegionUser(id, Integer.parseInt(state));
        } else if (state.equals("6")) {
             ucenterUser = apiService.selectRegionUser(id, Integer.parseInt(state));
        } else {
             ucenterUser = apiService.selectRegionUser(id, Integer.parseInt(state));

        }
        UcenterAuthInfoExample example = new UcenterAuthInfoExample();
        example.createCriteria().andUserIdEqualTo(ucenterUser.getId());
        UcenterAuthInfoExample example1 = new UcenterAuthInfoExample();
        example1.createCriteria().andUserIdEqualTo(ucenterUser.getId()).andAuthTypeEqualTo(Integer.parseInt(state));
        List<UcenterAuthInfo> list = apiService.selectUcenterAuthInfo(example);
        List<UcenterAuthInfo> list1 = apiService.selectUcenterAuthInfo(example1);
        UcenterUserCityExample ucenterUserCityExample = new UcenterUserCityExample();
        ucenterUserCityExample.createCriteria().andUserIdEqualTo(ucenterUser.getId());
        UcenterUserCity  ucenterUserCities = apiService.getUserCity(ucenterUserCityExample);
        UcenterUserCityExample ucenterUserCityExample1 = new UcenterUserCityExample();
        ucenterUserCityExample1.createCriteria().andUserIdEqualTo(ucenterUser.getId());
        List<UcenterUserCity> citylist  = apiService.selectUserCity(ucenterUserCityExample);
        if(null!=citylist){
            ucenterUser.setUcenterUserCities(citylist);
        }
        if(null!=list1&&0!=list1.size()){
            ucenterUser.setAuthInfo(list1.get(0).getAuthType());
            ucenterUser.setAuthInfoId(list1.get(0).getId());
        }
        if(null!=list&&0!=list.size()){
            ucenterUser.setUcenterAuthInfos(list);
        }
        if(null!=ucenterUserCities){
            ConfigRegionExample configRegionExample = new ConfigRegionExample();
            configRegionExample.createCriteria().andRegionIdEqualTo(ucenterUserCities.getCityId());
            ConfigRegion configRegion = apiService.selectAddressRegion(configRegionExample);
            ucenterUser.setRegionId(configRegion.getRegionId());
            ucenterUser.setRegionName(configRegion.getRegionName());
            ucenterUser.setRegionNumber(configRegion.getRegionNumber().intValue());
        }

        return ucenterUser;
    }

    @RequestMapping(value = "/gpsWX/gpsToBaidu", method = RequestMethod.POST)
    @ResponseBody
    public Object gpsToBaidu(Model model, HttpServletRequest request, String latitude, String longitude, String accuracy, int state) {
        byte[] a = UcenterUserUtils.getUser(request.getSession());
        if (null == a) {
            model.addAttribute("data", "您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return thymeleaf("/404");
        }
        UcenterUser ucenterUser = (UcenterUser) ByteUtils.ByteToObject(a);
        if (null == ucenterUser) {
            model.addAttribute("data", "您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return thymeleaf("/404");
        }
        Map<String,String> map = WxGetGpsUtils.processRequest(request, latitude, longitude, accuracy);
        int code1 = Integer.parseInt(map.get("adcode"));
        ConfigRegionExample configRegionExample = new ConfigRegionExample();
        configRegionExample.createCriteria().andRegionNumberEqualTo((long) code1);
        ConfigRegion configRegiog = apiService.selectAddressRegion(configRegionExample);

        UcenterUserCity ucenterUserCity = new UcenterUserCity();
        ucenterUserCity.setCityId(configRegiog.getRegionId());
        ucenterUserCity.setUserId(ucenterUser.getId());
        ucenterUserCity.setLat(Double.valueOf(map.get("lat")));
        ucenterUserCity.setLng(Double.valueOf(map.get("lng")));
        ucenterUserCity.setState(1);
        GeoHash geoHash = GeoHash.fromCoordinate(ucenterUserCity.getLat(),ucenterUserCity.getLng());
        //4024744861876082L
        long longValue = geoHash.toLong();
        ucenterUserCity.setAddress(map.get("address"));
        ucenterUserCity.setGenCode(longValue);
        apiService.insertCity(ucenterUserCity);
        JSONObject object = JSONObject.fromObject(ucenterUserCity);
        String key1 = "address"+ucenterUser.getId();
        RedisUtil.saddList(key1,object.toString());
        RedisUtil.del_add("dangqianweizhi"+ucenterUser.getId(),object.toString());
        String key = "addressKey" + ucenterUser.getId().toString();
        RedisUtil.del_save(key.getBytes(), ByteUtils.ObjectToByte(configRegiog));
        return new WxplatformResult(WxplatformResultConstant.SUCCESS, configRegiog);

    }
    @RequestMapping(value = "/gpsWX/gpsSaveAddress", method = RequestMethod.POST)
    @ResponseBody
    public Object gpsSaveAddress(Model model, HttpServletRequest request, String latitude, String longitude, String accuracy, int state) {
        byte[] a = UcenterUserUtils.getUser(request.getSession());
        if (null == a) {
            model.addAttribute("data", "您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return thymeleaf("/404");
        }
        UcenterUser ucenterUser = (UcenterUser) ByteUtils.ByteToObject(a);
        if (null == ucenterUser) {
            model.addAttribute("data", "您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return thymeleaf("/404");
        }
        Map<String,String> map = WxGetGpsUtils.processAddreess(request, latitude, longitude, accuracy);
        int code1 = Integer.parseInt(map.get("adcode"));
        ConfigRegionExample configRegionExample = new ConfigRegionExample();
        configRegionExample.createCriteria().andRegionNumberEqualTo((long) code1);
        ConfigRegion configRegiog = apiService.selectAddressRegion(configRegionExample);
        UcenterUserCityExample ucenterUserCityExample = new UcenterUserCityExample();
        ucenterUserCityExample.createCriteria().andUserIdEqualTo(ucenterUser.getId());
        List<UcenterUserCity> list =  apiService.selectUserCity(ucenterUserCityExample);
        if(null!=list&&0!=list.size()){
            for(UcenterUserCity ucenterUserCity:list){
                ucenterUserCity.setState(0);
                apiService.updateCity(ucenterUserCity);
            }
        }

        UcenterUserCity ucenterUserCity = new UcenterUserCity();
        ucenterUserCity.setCityId(configRegiog.getRegionId());
        ucenterUserCity.setUserId(ucenterUser.getId());
        ucenterUserCity.setLat(Double.valueOf(map.get("lat")));
        ucenterUserCity.setLng(Double.valueOf(map.get("lng")));
        ucenterUserCity.setState(1);
        GeoHash geoHash = GeoHash.fromCoordinate(ucenterUserCity.getLat(),ucenterUserCity.getLng());
        //4024744861876082L
        long longValue = geoHash.toLong();
        ucenterUserCity.setAddress(map.get("address"));
        ucenterUserCity.setGenCode(longValue);
        apiService.insertCity(ucenterUserCity);
        JSONObject object = JSONObject.fromObject(ucenterUserCity);
        String key1 = "address"+ucenterUser.getId();
        RedisUtil.saddList(key1,object.toString());
        RedisUtil.del_add("dangqianweizhi"+ucenterUser.getId(),object.toString());
        String key = "addressKey" + ucenterUser.getId().toString();
        RedisUtil.del_save(key.getBytes(), ByteUtils.ObjectToByte(configRegiog));
        return new WxplatformResult(WxplatformResultConstant.SUCCESS, configRegiog);

    }
    private void toRedisAddress(UcenterUser ucenterUser) {
        ConfigRegionExample configRegionExample = new ConfigRegionExample();
        configRegionExample.createCriteria().andRegionIdEqualTo(ucenterUser.getRegionId());
        ConfigRegion configRegiog = apiService.selectAddressRegion(configRegionExample);
        UcenterUserCityExample ucenterUserCityExample = new UcenterUserCityExample();
        ucenterUserCityExample.createCriteria().andUserIdEqualTo(ucenterUser.getId()).andStateEqualTo(1);
        UcenterUserCity ucenterUserCity = apiService.getUserCity(ucenterUserCityExample);
        JSONObject object = JSONObject.fromObject(ucenterUserCity);
        RedisUtil.del_add("dangqianweizhi"+ucenterUser.getId(),object.toString());
        String key = "addressKey" + ucenterUser.getId().toString();
        System.out.println(ucenterUser.getId());
        RedisUtil.del_save(key.getBytes(), ByteUtils.ObjectToByte(configRegiog));
    }

    private void toRedisUser(UcenterUser ucenterUser, HttpSession session) {
        session.setAttribute(HZF_WX_CLIENT_SESSION_ID + "userid", ucenterUser.getId());
        String key1 = "user" + ucenterUser.getId().toString();
        RedisUtil.del_save(key1.getBytes(), ByteUtils.ObjectToByte(ucenterUser));
    }
}
